package org.framework.lazy.cloud.network.heartbeat.server.standalone.infrastructure.persistence;

import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import jakarta.annotation.Resource;
import org.framework.lazy.cloud.network.heartbeat.common.ChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.constant.ProxyMessageType;
import org.framework.lazy.cloud.network.heartbeat.protocol.route.RouteContext;
import org.framework.lazy.cloud.network.heartbeat.protocol.route.RouteType;
import org.framework.lazy.cloud.network.heartbeat.protocol.route.ServerProxyRoute;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.netty.server.virtual.route.LazyNettyServerVirtualRoute;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.netty.server.virtual.route.LazyNettyServerVirtualRouteRepository;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.infrastructure.converter.LazyNettyServerVirtualRouteConverter;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.infrastructure.entity.LazyNettyServerVirtualRouteDO;
import org.springframework.stereotype.Repository;
import org.wu.framework.lazy.orm.database.lambda.domain.LazyPage;
import org.wu.framework.lazy.orm.database.lambda.stream.lambda.LazyLambdaStream;
import org.wu.framework.lazy.orm.database.lambda.stream.wrapper.LazyUpdateSetValueWrappers;
import org.wu.framework.lazy.orm.database.lambda.stream.wrapper.LazyWrappers;
import org.wu.framework.web.response.Result;
import org.wu.framework.web.response.ResultFactory;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

/**
 * describe 服务端虚拟路由管理
 *
 * @author Jia wei Wu
 * @date 2025/05/06 05:00 下午
 * @see org.wu.framework.lazy.orm.core.persistence.reverse.lazy.ddd.DefaultDDDLazyInfrastructurePersistence
 **/
@Repository
public class LazyNettyServerVirtualRouteRepositoryImpl implements LazyNettyServerVirtualRouteRepository {

    @Resource
    LazyLambdaStream lazyLambdaStream;

    /**
     * describe 新增服务端虚拟路由管理
     *
     * @param lazyNettyServerVirtualRoute 新增服务端虚拟路由管理
     * @return {@link Result<LazyNettyServerVirtualRoute>} 服务端虚拟路由管理新增后领域对象
     * @author Jia wei Wu
     * @date 2025/05/06 05:00 下午
     **/

    @Override
    public Result<LazyNettyServerVirtualRoute> story(LazyNettyServerVirtualRoute lazyNettyServerVirtualRoute) {
        // 验证ip是否存在
        //数据下发

        LazyNettyServerVirtualRouteDO lazyNettyServerVirtualRouteDO = LazyNettyServerVirtualRouteConverter.INSTANCE.fromLazyNettyServerVirtualRoute(lazyNettyServerVirtualRoute);
        lazyLambdaStream.upsert(lazyNettyServerVirtualRouteDO);

        // 更新服务端路由
        String virtualIp = lazyNettyServerVirtualRoute.getVirtualIp();
        String virtualPort = lazyNettyServerVirtualRoute.getVirtualPort();
        String targetIp = lazyNettyServerVirtualRoute.getTargetIp();
        String targetPort = lazyNettyServerVirtualRoute.getTargetPort();


        ServerProxyRoute serverProxyRoute = new ServerProxyRoute();

        serverProxyRoute.setVirtualIp(virtualIp);
        serverProxyRoute.setVirtualPort(virtualPort);
        serverProxyRoute.setTargetIp(targetIp);
        serverProxyRoute.setTargetPort(targetPort);
        serverProxyRoute.setRouteType(RouteType.LOCAL);
        RouteContext.setRoute(serverProxyRoute);

        ServerProxyRoute clientProxyServerRoute = new ServerProxyRoute();
        clientProxyServerRoute.setVirtualIp(virtualIp);
        clientProxyServerRoute.setVirtualPort(virtualPort);
        clientProxyServerRoute.setTargetIp(targetIp);
        clientProxyServerRoute.setTargetPort(targetPort);
        clientProxyServerRoute.setRouteType(RouteType.CLIENT_PROXY_SEVER);
        // 发送所有客户端本地路由刷新
        ChannelContext.getChannels().forEach((clientId, channels) -> {
            NettyProxyMsg nettyMsg = new NettyProxyMsg();
            nettyMsg.setType(ProxyMessageType.HTTP_DISTRIBUTE_CLIENT_PROXY_SERVER_SERVER_ROUTE_);
            nettyMsg.setData((JSON.toJSONString(clientProxyServerRoute)
                    .getBytes(StandardCharsets.UTF_8)));
            // 发送所有客户端ID
            for (Channel channel : channels) {
                channel.writeAndFlush(nettyMsg);
            }
        });
        return ResultFactory.successOf();
    }

    /**
     * describe 批量新增服务端虚拟路由管理
     *
     * @param lazyNettyServerVirtualRouteList 批量新增服务端虚拟路由管理
     * @return {@link Result<List<LazyNettyServerVirtualRoute>>} 服务端虚拟路由管理新增后领域对象集合
     * @author Jia wei Wu
     * @date 2025/05/06 05:00 下午
     **/

    @Override
    public Result<List<LazyNettyServerVirtualRoute>> batchStory(List<LazyNettyServerVirtualRoute> lazyNettyServerVirtualRouteList) {
        List<LazyNettyServerVirtualRouteDO> lazyNettyServerVirtualRouteDOList = lazyNettyServerVirtualRouteList.stream().map(LazyNettyServerVirtualRouteConverter.INSTANCE::fromLazyNettyServerVirtualRoute).collect(Collectors.toList());
        lazyLambdaStream.upsert(lazyNettyServerVirtualRouteDOList);
        return ResultFactory.successOf();
    }

    /**
     * describe 查询单个服务端虚拟路由管理
     *
     * @param lazyNettyServerVirtualRoute 查询单个服务端虚拟路由管理
     * @return {@link Result<LazyNettyServerVirtualRoute>} 服务端虚拟路由管理领域对象
     * @author Jia wei Wu
     * @date 2025/05/06 05:00 下午
     **/

    @Override
    public Result<LazyNettyServerVirtualRoute> findOne(LazyNettyServerVirtualRoute lazyNettyServerVirtualRoute) {
        LazyNettyServerVirtualRouteDO lazyNettyServerVirtualRouteDO = LazyNettyServerVirtualRouteConverter.INSTANCE.fromLazyNettyServerVirtualRoute(lazyNettyServerVirtualRoute);
        lazyNettyServerVirtualRouteDO.setIsDeleted(false);
        LazyNettyServerVirtualRoute lazyNettyServerVirtualRouteOne = lazyLambdaStream.selectOne(LazyWrappers.lambdaWrapperBean(lazyNettyServerVirtualRouteDO), LazyNettyServerVirtualRoute.class);
        return ResultFactory.successOf(lazyNettyServerVirtualRouteOne);
    }

    /**
     * describe 查询多个服务端虚拟路由管理
     *
     * @param lazyNettyServerVirtualRoute 查询多个服务端虚拟路由管理
     * @return {@link Result<List<LazyNettyServerVirtualRoute>>} 服务端虚拟路由管理领域对象
     * @author Jia wei Wu
     * @date 2025/05/06 05:00 下午
     **/

    @Override
    public Result<List<LazyNettyServerVirtualRoute>> findList(LazyNettyServerVirtualRoute lazyNettyServerVirtualRoute) {
        LazyNettyServerVirtualRouteDO lazyNettyServerVirtualRouteDO = LazyNettyServerVirtualRouteConverter.INSTANCE.fromLazyNettyServerVirtualRoute(lazyNettyServerVirtualRoute);
        List<LazyNettyServerVirtualRoute> lazyNettyServerVirtualRouteList = lazyLambdaStream.selectList(LazyWrappers.lambdaWrapperBean(lazyNettyServerVirtualRouteDO), LazyNettyServerVirtualRoute.class);
        return ResultFactory.successOf(lazyNettyServerVirtualRouteList);
    }

    /**
     * describe 分页查询多个服务端虚拟路由管理
     *
     * @param size                        当前页数
     * @param current                     当前页
     * @param lazyNettyServerVirtualRoute 分页查询多个服务端虚拟路由管理
     * @return {@link Result<LazyPage<LazyNettyServerVirtualRoute>>} 分页服务端虚拟路由管理领域对象
     * @author Jia wei Wu
     * @date 2025/05/06 05:00 下午
     **/

    @Override
    public Result<LazyPage<LazyNettyServerVirtualRoute>> findPage(int size, int current, LazyNettyServerVirtualRoute lazyNettyServerVirtualRoute) {
        LazyNettyServerVirtualRouteDO lazyNettyServerVirtualRouteDO = LazyNettyServerVirtualRouteConverter.INSTANCE.fromLazyNettyServerVirtualRoute(lazyNettyServerVirtualRoute);
        LazyPage<LazyNettyServerVirtualRoute> lazyPage = new LazyPage<>(current, size);
        LazyPage<LazyNettyServerVirtualRoute> lazyNettyServerVirtualRouteLazyPage = lazyLambdaStream.selectPage(LazyWrappers.lambdaWrapperBean(lazyNettyServerVirtualRouteDO), lazyPage, LazyNettyServerVirtualRoute.class);
        return ResultFactory.successOf(lazyNettyServerVirtualRouteLazyPage);
    }

    /**
     * describe 删除服务端虚拟路由管理
     *
     * @param lazyNettyServerVirtualRoute 删除服务端虚拟路由管理
     * @return {@link Result<LazyNettyServerVirtualRoute>} 服务端虚拟路由管理
     * @author Jia wei Wu
     * @date 2025/05/06 05:00 下午
     **/

    @Override
    public Result<LazyNettyServerVirtualRoute> remove(LazyNettyServerVirtualRoute lazyNettyServerVirtualRoute) {
        LazyNettyServerVirtualRouteDO lazyNettyServerVirtualRouteDO = LazyNettyServerVirtualRouteConverter.INSTANCE.fromLazyNettyServerVirtualRoute(lazyNettyServerVirtualRoute);
        lazyLambdaStream.update(LazyUpdateSetValueWrappers.<LazyNettyServerVirtualRouteDO>lambdaWrapper()
                        .set(LazyNettyServerVirtualRouteDO::getIsDeleted, true),
                LazyWrappers
                        .<LazyNettyServerVirtualRouteDO>lambdaWrapper()
                        .eq(LazyNettyServerVirtualRouteDO::getId, lazyNettyServerVirtualRouteDO.getId())

        );

        LazyNettyServerVirtualRouteDO virtualRouteDO = lazyLambdaStream.selectOne(
                LazyWrappers.<LazyNettyServerVirtualRouteDO>lambdaWrapper()
                        .eq(LazyNettyServerVirtualRouteDO::getId, lazyNettyServerVirtualRouteDO.getId())
        );
        String virtualIp = virtualRouteDO.getVirtualIp();
        String virtualPort = virtualRouteDO.getVirtualPort();
        String targetIp = virtualRouteDO.getTargetIp();
        String targetPort = virtualRouteDO.getTargetPort();


        ServerProxyRoute clientProxyServerRoute = new ServerProxyRoute();
        clientProxyServerRoute.setVirtualIp(virtualIp);
        clientProxyServerRoute.setVirtualPort(virtualPort);
        clientProxyServerRoute.setTargetIp(targetIp);
        clientProxyServerRoute.setTargetPort(targetPort);
        clientProxyServerRoute.setRouteType(RouteType.CLIENT_PROXY_SEVER);
        // 发送所有客户端本地路由刷新
        ChannelContext.getChannels().forEach((clientId, channels) -> {
            NettyProxyMsg nettyMsg = new NettyProxyMsg();
            nettyMsg.setType(ProxyMessageType.HTTP_DISTRIBUTE_CLIENT_PROXY_SERVER_SERVER_ROUTE_CLOSE_);
            nettyMsg.setData((JSON.toJSONString(clientProxyServerRoute)
                    .getBytes(StandardCharsets.UTF_8)));
            // 发送所有客户端ID
            for (Channel channel : channels) {
                channel.writeAndFlush(nettyMsg);
            }
        });
        return ResultFactory.successOf();
    }

    /**
     * describe 是否存在服务端虚拟路由管理
     *
     * @param lazyNettyServerVirtualRoute 服务端虚拟路由管理领域对象
     * @return {@link Result<Boolean>} 是否存在 true 存在，false 不存在
     * @author Jia wei Wu
     * @date 2025/05/06 05:00 下午
     **/

    @Override
    public Result<Boolean> exists(LazyNettyServerVirtualRoute lazyNettyServerVirtualRoute) {
        LazyNettyServerVirtualRouteDO lazyNettyServerVirtualRouteDO = LazyNettyServerVirtualRouteConverter.INSTANCE.fromLazyNettyServerVirtualRoute(lazyNettyServerVirtualRoute);
        Boolean exists = lazyLambdaStream.exists(LazyWrappers.lambdaWrapperBean(lazyNettyServerVirtualRouteDO));
        return ResultFactory.successOf(exists);
    }

}